<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
    <title>顾客预约管理</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.min.css">
    <style>
        body {
            background-color: #f8f9fa;
            padding-top: 15px;
            padding-bottom: 20px;
        }
        .card {
            margin-bottom: 15px;
            border-radius: 10px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
        }
        .card-header {
            background-color: #28a745;
            color: white;
            border-radius: 10px 10px 0 0 !important;
        }
        .btn-primary {
            background-color: #007bff;
        }
        .reservation-status {
            font-weight: bold;
        }
        .status-1 {color: #ffc107;} /* 待确认 */
        .status-2 {color: #17a2b8;} /* 已确认 */
        .status-3 {color: #28a745;} /* 已完成 */
        .status-4 {color: #dc3545;} /* 已取消 */
        .no-data {
            text-align: center;
            padding: 20px;
            color: #6c757d;
        }
        .btn-circle {
            width: 60px;
            height: 60px;
            padding: 10px;
            border-radius: 30px;
            font-size: 18px;
            line-height: 1.33;
            position: fixed;
            right: 20px;
            bottom: 20px;
            z-index: 100;
            box-shadow: 0 4px 8px rgba(0,0,0,0.2);
        }
        .form-group {
            margin-bottom: 1rem;
        }
        .modal-header {
            background-color: #28a745;
            color: white;
        }
        .close {
            color: white;
        }
        .close:hover {
            color: #f8f9fa;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="row">
            <div class="col-12">
                <h4 class="text-center mb-4">我的预约</h4>
                <div id="loading" class="text-center">
                    <div class="spinner-border text-primary" role="status">
                        <span class="sr-only">加载中...</span>
                    </div>
                    <p>正在验证身份...</p>
                </div>
                
                <div id="unauthorized" class="alert alert-danger text-center" style="display:none;">
                    <strong>无访问权限!</strong> 您不是注册顾客，无法访问此页面。
                </div>
                
                <div id="error" class="alert alert-danger text-center" style="display:none;">
                    <strong>出错了!</strong> <span id="errorMsg">加载数据时出错</span>
                </div>
                
                <div id="mainContent" style="display:none;">
                    <div class="form-group">
                        <select class="form-control" id="statusFilter">
                            <option value="">全部状态</option>
                            <option value="1">待确认</option>
                            <option value="2">已确认</option>
                            <option value="3">已完成</option>
                            <option value="4">已取消</option>
                        </select>
                    </div>
                    
                    <div id="reservationsList">
                        <!-- 预约列表将通过JS动态加载 -->
                    </div>
                    
                    <!-- 新增预约按钮 -->
                    <button class="btn btn-success btn-circle" data-toggle="modal" data-target="#newReservationModal">
                        <i class="fas fa-plus">+</i>
                    </button>
                </div>
            </div>
        </div>
    </div>
    
    <!-- 新增预约模态框 -->
    <div class="modal fade" id="newReservationModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">新增预约</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <form id="reservationForm">
                        <div class="form-group">
                            <label for="serviceContent">服务内容</label>
                            <select class="form-control" id="serviceContent" required>
                                <option value="">请选择服务项目</option>
                                <option value="面部护理">面部护理</option>
                                <option value="身体按摩">身体按摩</option>
                                <option value="SPA套餐">SPA套餐</option>
                                <option value="美甲服务">美甲服务</option>
                                <option value="其他服务">其他服务</option>
                            </select>
                        </div>
                        <div class="form-group">
                            <label for="staffSelect">选择技师</label>
                            <select class="form-control" id="staffSelect">
                                <option value="">不指定技师</option>
                                <!-- 技师列表将通过JS动态加载 -->
                            </select>
                        </div>
                        <div class="form-group">
                            <label for="appointmentDate">预约日期</label>
                            <input type="date" class="form-control" id="appointmentDate" required>
                        </div>
                        <div class="form-group">
                            <label for="appointmentTime">预约时间</label>
                            <input type="time" class="form-control" id="appointmentTime" required>
                        </div>
                        <div class="form-group">
                            <label for="remark">备注信息</label>
                            <textarea class="form-control" id="remark" rows="3"></textarea>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" id="submitReservation">提交预约</button>
                </div>
            </div>
        </div>
    </div>
    
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.5.1/dist/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/js/bootstrap.min.js"></script>
    <script>
        // 定义全局变量存储微信openid和顾客信息
        var wxOpenid = "";
        var customerInfo = null;
        
        $(document).ready(function() {
            // 获取URL参数中的openid
            const urlParams = new URLSearchParams(window.location.search);
            wxOpenid = urlParams.get('openid') || "";
            
            if (!wxOpenid) {
                showError("缺少必要的微信授权信息，请重新进入");
                return;
            }
            
            // 验证顾客身份
            verifyCustomerIdentity();
            
            // 绑定事件
            $('#statusFilter').change(function() {
                loadReservations();
            });
            
            $('#submitReservation').click(function() {
                submitReservation();
            });
            
            // 设置日期最小值为今天
            const today = new Date().toISOString().split('T')[0];
            $('#appointmentDate').attr('min', today);
        });
        
        // 验证顾客身份
        function verifyCustomerIdentity() {
            $.ajax({
                url: '/wx/verifyCustomerIdentity',
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify({ openid: wxOpenid }),
                success: function(response) {
                    if (response.code === 200) {
                        customerInfo = response.data;
                        $('#loading').hide();
                        $('#mainContent').show();
                        
                        // 加载预约数据和技师列表
                        loadReservations();
                        loadStaffList();
                    } else {
                        $('#loading').hide();
                        $('#unauthorized').show();
                    }
                },
                error: function(xhr) {
                    $('#loading').hide();
                    showError("验证身份失败: " + (xhr.responseJSON ? xhr.responseJSON.msg : "未知错误"));
                }
            });
        }
        
        // 加载预约列表
        function loadReservations() {
            if (!customerInfo) return;
            
            const status = $('#statusFilter').val();
            
            $('#reservationsList').html('<div class="text-center p-3"><div class="spinner-border spinner-border-sm text-primary"></div> 加载中...</div>');
            
            $.ajax({
                url: '/wx/getCustomerReservations',
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify({ 
                    openid: wxOpenid,
                    customerPid: customerInfo.pid,
                    status: status
                }),
                success: function(response) {
                    if (response.code === 200) {
                        renderReservations(response.data);
                    } else {
                        $('#reservationsList').html('<div class="alert alert-danger">加载预约失败: ' + response.msg + '</div>');
                    }
                },
                error: function() {
                    $('#reservationsList').html('<div class="alert alert-danger">网络错误，请稍后重试</div>');
                }
            });
        }
        
        // 渲染预约列表
        function renderReservations(reservations) {
            if (!reservations || reservations.length === 0) {
                $('#reservationsList').html('<div class="no-data">暂无预约记录</div>');
                return;
            }
            
            let html = '';
            
            reservations.forEach(function(item) {
                const statusText = getStatusText(item.status);
                const statusClass = `status-${item.status}`;
                
                html += `
                <div class="card">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        <div>${item.serviceContent}</div>
                        <span class="reservation-status ${statusClass}">${statusText}</span>
                    </div>
                    <div class="card-body">
                        <p class="card-text"><strong>预约时间:</strong> ${formatDateTime(item.appointmentTime)}</p>
                        <p class="card-text"><strong>服务技师:</strong> ${item.staffName || '未分配'}</p>
                        <p class="card-text"><strong>服务房间:</strong> ${item.roomNo || '未分配'}</p>
                        
                        <div class="text-right mt-2">`;
                
                // 根据状态显示不同按钮
                if (item.status === 1) { // 待确认
                    html += `<button class="btn btn-sm btn-danger" onclick="cancelReservation(${item.id})">取消预约</button>`;
                }
                
                html += `
                        </div>
                    </div>
                </div>`;
            });
            
            $('#reservationsList').html(html);
        }
        
        // 加载技师列表
        function loadStaffList() {
            $.ajax({
                url: '/wx/getStaffList',
                type: 'GET',
                success: function(response) {
                    if (response.code === 200) {
                        let options = '<option value="">不指定技师</option>';
                        response.data.forEach(function(staff) {
                            options += `<option value="${staff.pid}">${staff.name}</option>`;
                        });
                        $('#staffSelect').html(options);
                    }
                }
            });
        }
        
        // 提交预约
        function submitReservation() {
            if (!customerInfo) {
                showError("用户信息未加载，请刷新页面重试");
                return;
            }
            
            // 表单验证
            const serviceContent = $('#serviceContent').val();
            const appointmentDate = $('#appointmentDate').val();
            const appointmentTime = $('#appointmentTime').val();
            
            if (!serviceContent || !appointmentDate || !appointmentTime) {
                alert("请填写完整的预约信息");
                return;
            }
            
            // 构建预约时间
            const appointmentDateTime = appointmentDate + 'T' + appointmentTime + ':00';
            
            // 构建请求数据
            const requestData = {
                openid: wxOpenid,
                customerPid: customerInfo.pid,
                customerName: customerInfo.name,
                customerPhone: customerInfo.phone,
                serviceContent: serviceContent,
                appointmentTime: appointmentDateTime,
                staffPid: $('#staffSelect').val() || null,
                remark: $('#remark').val() || ''
            };
            
            // 发送请求
            $.ajax({
                url: '/wx/createReservation',
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify(requestData),
                success: function(response) {
                    if (response.code === 200) {
                        alert('预约提交成功，请等待商家确认');
                        $('#newReservationModal').modal('hide');
                        // 重置表单
                        $('#reservationForm')[0].reset();
                        // 刷新预约列表
                        loadReservations();
                    } else {
                        alert('预约失败: ' + response.msg);
                    }
                },
                error: function() {
                    alert('网络错误，请稍后重试');
                }
            });
        }
        
        // 取消预约
        function cancelReservation(id) {
            if (!confirm('确定要取消此预约吗？')) return;
            
            $.ajax({
                url: '/wx/cancelReservation',
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify({ 
                    id: id,
                    openid: wxOpenid
                }),
                success: function(response) {
                    if (response.code === 200) {
                        alert('预约已取消');
                        loadReservations();
                    } else {
                        alert('取消失败: ' + response.msg);
                    }
                },
                error: function() {
                    alert('网络错误，请稍后重试');
                }
            });
        }
        
        // 显示错误信息
        function showError(message) {
            $('#loading').hide();
            $('#errorMsg').text(message);
            $('#error').show();
        }
        
        // 格式化日期时间
        function formatDateTime(timestamp) {
            if (!timestamp) return '未设置';
            const date = new Date(timestamp);
            return date.getFullYear() + '-' + 
                   padZero(date.getMonth() + 1) + '-' + 
                   padZero(date.getDate()) + ' ' + 
                   padZero(date.getHours()) + ':' + 
                   padZero(date.getMinutes());
        }
        
        // 数字补零
        function padZero(num) {
            return num < 10 ? '0' + num : num;
        }
        
        // 获取预约状态文字
        function getStatusText(status) {
            switch (status) {
                case 1: return '待确认';
                case 2: return '已确认';
                case 3: return '已完成';
                case 4: return '已取消';
                default: return '未知状态';
            }
        }
    </script>
</body>
</html> 